'''
Description:  play motion by http
Version: V1.0
Author: zw_1520@163.com
Date: 2025-04-22 10:22:22
LastEditors: zw_1520@163.com
LastEditTime: 2025-09-25 17:21:11
All rights reserved.
'''

import base64
import json
import requests
import time
from datetime import datetime
import agibot_controller.motion_control_service


def set_status(ip, status):
    """Sets interaction status"""
    # InteractionStatus definition
    # InteractionStatus_Ready = 0  # Ready
    # InteractionStatus_Talk  = 1  # Talk
    # InteractionStatus_Task  = 2  # Task

    # Constructs data
    data = {
        "status": status
    }
    # Sends post request
    session = requests.Session()
    response = session.post(
        url='http://'+ip+':59201/rpc/aimdk.protocol.InteractionStatusService/SetStatus',
        headers={'content-type': 'application/json'},
        data=json.dumps(data, ensure_ascii=False)
    )


def get_status(ip):
    """Gets interaction status"""
    # Sends post request.
    session = requests.Session()
    response = session.post(
        url='http://'+ip+':59201/rpc/aimdk.protocol.InteractionStatusService/GetStatus',
        headers={'content-type': 'application/json'},
        data=json.dumps({}))
    # Prints response
    # print(f"Response status: {response.status_code}")
    # print(f"Response header: {response.headers}")
    print(f"Response:", json.loads(response.text)["status"])
    return json.loads(response.text)["status"]


def get_task_status(ip):
    """Gets task status"""
    # Sends post request
    session = requests.Session()
    response = session.post(
        url='http://'+ip+':59201/rpc/aimdk.protocol.InteractionTaskService/GetInteractionTaskStatus',
        headers={'content-type': 'application/json'},
        data=json.dumps({}))
    # Prints log
    # print(f"[GetStatus 响应]")
    # print(f"Status code: {response.status_code}")
    # print(f"Response headers: {response.headers}")
    print(f"Response:", json.loads(response.text)["status"])
    # return json.loads(response.text)["status"]


def encoded_text(text):
    text = text
    encoded_bytes = base64.b64encode(text.encode('utf-8'))
    encoded_text = encoded_bytes.decode('utf-8')

    return encoded_text


def post_data(text, motion, face):
    """Posts data """
    data = {
        "task": {
            "task_name": "interaction_task",
            "interaction_list": [
                {
                    "text": encoded_text(text),
                    "motion_name": motion,  # Motion id
                    "face_expression": face  # Faces id
                }
            ],
            "task_type": 0
        }
    }
    return data


def motion_data(motion_id, duration_ms):
    """ Constructs motion data"""
    data = {
        "motion_id": "{motion_id}",
        "duration_ms": duration_ms,
        "cmd_end": True,
        "cmd_pause": False,
        "cmd_reset": False
    }
    return data


def play_motion_by_http(motion_id, duration_ms):
    """Plays motion"""

    # Sets robot status
    motion_service = agibot_controller.motion_control_service.MotionControlService()
    motion_service.ensure_action('RL_LOCOMOTION_ARM_EXT_JOINT_SERVO')

    # InteractionStatus definition
    # InteractionStatus_Ready = 0  # Ready
    # InteractionStatus_Talk  = 1  # Talk
    # InteractionStatus_Task  = 2  # Task

    # Constructs data
    data = motion_data(
        motion_id, duration_ms)
    print(f"data: {data}")
    # Sends post request
    session = requests.Session()
    orin_ip = '192.168.100.100'
    # http://$IP_ADDRESS/rpc/aimdk.protocol.MotionCommandService/SendMotionCommand
    # response = session.post(
    #     url=ip+'/rpc/aimdk.protocol.MotionCommandService/SendMotionCommand',
    #     headers={'content-type': 'application/json'},
    #     data=json.dumps(data, ensure_ascii=False)
    # )
    response = requests.post(
        url='http://'+orin_ip +
            ':56444/rpc/aimdk.protocol.MotionCommandService/SendMotionCommand',
        headers={'content-type': 'application/json'},
        data=json.dumps(data,
                        ensure_ascii=False)  # Closes ascii for chinese
    )


def get_current_motion_id():
    x86_ip = '192.168.100.100'
    session = requests.Session()
    response = session.post(
        url='http://'+x86_ip+':59001/rpc/aimdk.protocol.RcMotionPlayerService/GetMotionList',
        headers={'content-type': 'application/json'},
        data=json.dumps({}))
    print(f"Response status: {response.status_code}")
    print(f"Response:", response.json())
    # Prints motion id and name
    id_list = []

    for motion in response.json().get("motion_list", []):
        id_list.append(motion.get("motion_id"))
        print(
            f"Motion ID: {motion['motion_id']}, Motion Name: {motion['motion_name']}")
    return id_list


def play_motion_id(motion_id):
    x86_ip = '192.168.100.100'
    motion_service = agibot_controller.motion_control_service.MotionControlService()
    motion_service.ensure_action('RL_LOCOMOTION_ARM_EXT_JOINT_SERVO')

    session = requests.Session()
    response = session.post(
        url='http://'+x86_ip+':59001/rpc/aimdk.protocol.RcMotionPlayerService/PlayerMotion',
        headers={'content-type': 'application/json'},
        data=json.dumps({"motion_id": str(motion_id)}))
    print(f"Response status: {response.status_code}")
    print(f"Response:", response.json())
    return response.json()


if __name__ == "__main__":
    # play_motion_by_http('/agibot/data/var/rc/motion_player/default/投篮/投篮')
    # Sets robot status
    motion_service = agibot_controller.motion_control_service.MotionControlService()
    motion_service.ensure_action('RL_LOCOMOTION_ARM_EXT_JOINT_SERVO')
    get_current_motion_id()
    play_motion_id(132)
